using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;

namespace OrderingSystem.Infrastructure.Services
{
    public class FavoriteService : IFavoriteService
    {
        private readonly ApplicationDbContext _context;

        public FavoriteService(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IEnumerable<Favorite>> GetFavoritesAsync()
        {
            return await _context.Favorites
                .Include(f => f.User)
                .OrderByDescending(f => f.addtime)
                .ToListAsync();
        }

        public async Task<IEnumerable<Favorite>> GetUserFavoritesAsync(long userId)
        {
            return await _context.Favorites
                .Include(f => f.User)
                .Where(f => f.userid == userId)
                .OrderByDescending(f => f.addtime)
                .ToListAsync();
        }

        public async Task<Favorite> GetFavoriteAsync(long id)
        {
            return await _context.Favorites
                .Include(f => f.User)
                .FirstOrDefaultAsync(f => f.id == id);
        }

        public async Task<Favorite> CreateFavoriteAsync(Favorite favorite)
        {
            // 检查是否已收藏
            var exists = await IsFavoritedAsync(favorite.userid, favorite.refid, favorite.leixing);
            if (exists)
            {
                return null;
            }

            favorite.addtime = DateTime.Now;
            _context.Favorites.Add(favorite);
            await _context.SaveChangesAsync();
            return favorite;
        }

        public async Task DeleteFavoriteAsync(long id)
        {
            var favorite = await _context.Favorites.FindAsync(id);
            if (favorite != null)
            {
                _context.Favorites.Remove(favorite);
                await _context.SaveChangesAsync();
            }
        }

        public async Task<bool> IsFavoritedAsync(long userId, long refId, string type)
        {
            return await _context.Favorites.AnyAsync(f => 
                f.userid == userId && 
                f.refid == refId && 
                f.leixing == type);
        }
    }
} 